#!/usr/bin/env python3

import requests
import json
import time
import os
from pathlib import Path

class HeroDataCollector:
    """武将数据采集器"""
    
    def __init__(self):
        self.mcp_url = "http://127.0.0.1:12306"
        self.data_dir = Path(__file__).parent.parent.parent / "database"
        self.data_dir.mkdir(exist_ok=True)
        
    def test_mcp_connection(self):
        """测试MCP连接"""
        try:
            response = requests.get(f"{self.mcp_url}/health", timeout=5)
            print(f"MCP服务器状态: {response.status_code}")
            return True
        except Exception as e:
            print(f"MCP连接失败: {e}")
            return False
    
    def navigate_to_hero_gallery(self):
        """导航到武将图鉴页面"""
        # 根据你的截图，武将图鉴的URL可能是这样的
        hero_gallery_url = "https://web.sanguosha.com/10/pc/index.php#/herobook"
        
        js_code = f"""
        // 导航到武将图鉴
        if (window.location.href !== '{hero_gallery_url}') {{
            window.location.href = '{hero_gallery_url}';
        }}
        
        // 等待页面加载
        setTimeout(() => {{
            console.log('已导航到武将图鉴页面');
            return '导航成功';
        }}, 2000);
        """
        
        return self.execute_js(js_code)
    
    def extract_hero_data(self):
        """提取当前页面的武将数据"""
        js_code = """
        // 提取武将信息的脚本
        const heroes = [];
        
        // 查找武将卡片元素（需要根据实际HTML结构调整选择器）
        const heroCards = document.querySelectorAll('.hero-card, .general-card, [class*="hero"], [class*="general"]');
        
        heroCards.forEach((card, index) => {
            try {
                const hero = {
                    id: index,
                    name: '',
                    faction: '',
                    cost: 0,
                    skills: [],
                    image_url: '',
                    description: ''
                };
                
                // 尝试提取武将名字
                const nameElement = card.querySelector('.hero-name, .name, h3, h4, [class*="name"]');
                if (nameElement) {
                    hero.name = nameElement.textContent.trim();
                }
                
                // 尝试提取势力信息
                const factionElement = card.querySelector('.faction, .kingdom, [class*="faction"], [class*="kingdom"]');
                if (factionElement) {
                    hero.faction = factionElement.textContent.trim();
                }
                
                // 尝试提取费用/星级
                const costElement = card.querySelector('.cost, .star, .level, [class*="cost"], [class*="star"]');
                if (costElement) {
                    const costText = costElement.textContent.trim();
                    const costMatch = costText.match(/\\d+/);
                    if (costMatch) {
                        hero.cost = parseInt(costMatch[0]);
                    }
                }
                
                // 尝试提取技能描述
                const skillElements = card.querySelectorAll('.skill, .ability, [class*="skill"], [class*="ability"]');
                skillElements.forEach(skillEl => {
                    if (skillEl.textContent.trim()) {
                        hero.skills.push(skillEl.textContent.trim());
                    }
                });
                
                // 尝试提取图片URL
                const imgElement = card.querySelector('img');
                if (imgElement) {
                    hero.image_url = imgElement.src || imgElement.dataset.src || '';
                }
                
                // 只保存有名字的武将
                if (hero.name) {
                    heroes.push(hero);
                }
            } catch (e) {
                console.warn('提取武将数据出错:', e);
            }
        });
        
        console.log(`提取到 ${heroes.length} 个武将信息:`, heroes);
        return heroes;
        """
        
        return self.execute_js(js_code)
    
    def execute_js(self, js_code):
        """执行JavaScript代码"""
        try:
            # 这里应该通过MCP API执行JS，但如果不可用就返回手动执行指令
            payload = {
                "method": "execute_js",
                "params": {
                    "code": js_code
                }
            }
            
            print(f"请在Chrome控制台中执行以下JavaScript代码:")
            print("="*50)
            print(js_code)
            print("="*50)
            print("然后将结果复制给我。")
            
            return "请手动执行JavaScript"
            
        except Exception as e:
            print(f"JavaScript执行失败: {e}")
            return None
    
    def save_hero_data(self, heroes_data):
        """保存武将数据到JSON文件"""
        if not heroes_data:
            print("没有武将数据可保存")
            return
            
        file_path = self.data_dir / "heroes.json"
        
        # 如果文件已存在，合并数据
        existing_data = []
        if file_path.exists():
            try:
                with open(file_path, 'r', encoding='utf-8') as f:
                    existing_data = json.load(f)
            except:
                pass
        
        # 合并新数据（避免重复）
        existing_names = {hero.get('name') for hero in existing_data}
        new_heroes = [hero for hero in heroes_data if hero.get('name') not in existing_names]
        
        all_heroes = existing_data + new_heroes
        
        with open(file_path, 'w', encoding='utf-8') as f:
            json.dump(all_heroes, f, ensure_ascii=False, indent=2)
        
        print(f"已保存 {len(all_heroes)} 个武将信息到 {file_path}")
        print(f"本次新增 {len(new_heroes)} 个武将")
    
    def collect_all_heroes(self):
        """采集所有武将数据的完整流程"""
        print("开始采集武将数据...")
        
        # 1. 测试连接
        if not self.test_mcp_connection():
            print("⚠️  MCP连接失败，将提供手动操作指令")
        
        # 2. 导航到图鉴页面
        print("\n📖 导航到武将图鉴...")
        self.navigate_to_hero_gallery()
        
        # 3. 提取数据
        print("\n📊 提取武将数据...")
        heroes_data = self.extract_hero_data()
        
        # 4. 提供后续步骤说明
        print("\n📝 后续步骤:")
        print("1. 在Chrome中打开三国杀自走棋")
        print("2. 找到武将图鉴/武将页面")
        print("3. 按F12打开开发者工具")
        print("4. 执行上面提供的JavaScript代码")
        print("5. 将结果告诉我，我会保存到数据库")
        
        return heroes_data


if __name__ == "__main__":
    collector = HeroDataCollector()
    collector.collect_all_heroes()